import { dialog } from "electron";
import { ISession } from "../types/session.ts";
import { ChatType, IMessage } from "../types/message.ts";

export async function selectFilePath(fileName: string, fileType: string): Promise<string | void> {
  const { canceled, filePath } = await dialog.showSaveDialog({
    title: "选择保存路径",
    defaultPath: fileName,
    filters: [
      {
        name: "." + fileType,
        extensions: [fileType],
      },
    ],
  });
  if (canceled || !filePath) return;
  return filePath;
}

export function buildSession(message: IMessage): ISession {
  let toId = message.chatType === ChatType.group ? message.groupId : message.sendId;

  // 如果是我们自己发的 说明 ownerId是 我们自己 to_id 是我们发送的to_id
  // 如果是别人发给我们的   ownerId是 message.toId  to_id 是对方的发送的send_id
  return {
    ownerId: message.toId,
    toId: toId!,
    chatType: message.chatType,
    sessionId: message.sessionId,
    sessionType: message.messageType,
    content: message.content!,
    updatedAt: message.updatedAt,
  };
}

export function Sort(arr: IMessage[], message: IMessage) {
  let low = 0,
    high = arr.length;
  while (low < high) {
    const mid = (low + high) >>> 1;
    if (arr[mid].updatedAt < message.updatedAt) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
  arr.splice(low, 0, message); // 插入到正确位置
}
